<template lang="pug">
.module-manage-add
  el-dialog(title="添加模块" v-model="dialogVisible" @close="handleClose" custom-class="dialog-width")
    el-scrollbar.scrollbar-dialog-wrap

      el-form(:model="state.form" ref="valiForm" :rules='state.forms' label-width="90px").form-width
        el-form-item(label="模块名:" prop='name')
          el-input(v-model="state.form.name" placeholder='模块名').form-input

        el-form-item
          el-button(@click="formSubmit('valiForm')" type="primary" size="small" :lodading="loading") 确定
          el-button(@click="handleClose" type="danger" size="small") 取消
</template>

<script setup>
import { ref, reactive, getCurrentInstance, watch, defineProps, defineEmit } from 'vue'

const { proxy } = getCurrentInstance()
const emit = defineEmit(['closeFun', 'update:isDialog'])
const props = defineProps({
  isDialog: {
    required: true
  },
  dialogRecord: {
    required: true
  }
})

const state = reactive({
  form: {
    name: '',
    pid: '',
    level: ''
  },
  forms: {
    name: [{ required: true, message: '模块名', trigger: 'blur' }]
  }
})
const valiForm = ref()
const dialogVisible = ref(false)
const loading = ref(false)

// 侦听
watch(() => [props.isDialog], ([newDialog, oldDialog]) => {
  if (!newDialog) return

  for (const key in state.form) {
    state.form[key] = ''
  }
  state.form.pid = props.dialogRecord.id
  state.form.level = (props.dialogRecord.level + 1)

  dialogVisible.value = newDialog
}, { immediate: true })

// 表达提交
function formSubmit (form) {
  valiForm.value.validate((valid) => {
    if (valid) {
      loading.value = true
      proxy.$message({ type: 'success', message: '提交成功' })
      emit('closeFun')
      handleClose()
    } else {
      return false
    }
  })
}

// 关闭弹窗
function handleClose () {
  emit('update:isDialog', false)
  dialogVisible.value = false
}
</script>
<style rel="stylesheet/scss" lang="scss">
</style>
